<template>
  <div id="goods-manage">
    <div class="search-box">
        <el-form>
            <el-form-item label="店铺类型：">
              <el-select v-model="form.shopType" placeholder="请选择店铺" size="small">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="(item, index) in shopTypeData" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="店铺名称：">
              <el-select v-model="form.shopId" placeholder="请选择店铺" size="small" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option v-for="(item, index) in shopListData" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品ID：">
              <el-input placeholder="请输入商品ID" v-model="form.productId" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="search-btn" icon="el-icon-ali-search" @click="getGoodsData()">查&nbsp;询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button class="reset-btn" icon="el-icon-ali-reset" @click="resetSearchParam">重&nbsp;置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button class="reset-btn" icon="el-icon-ali-add-1" @click="isShowAddGoods = true">添加商品</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table-box">
	  <div class="tips">*点击下面的商品可以进行更新商品信息</div>
      <div class="goods-list">
          <div class="img-box" v-for="(item,index) in goodsData" :key="index" >
            <i class="el-icon-error close-btn"  @click.stop="showConfirm(item.id)"></i>
            <div @click="getShopId(item)">
              <img v-if="item.goods_img.indexOf('blob')>=0" src="../../assets/image/placeholder_img.png" class="img" alt="">
              <img v-else :src="item.goods_img" class="img" alt="">
              <div class="text">店铺名称:{{item.shop_name}}</div>
              <div class="text">商品ID:{{item.product_id}}</div>
            </div>
            <el-checkbox :label="item.pay_money" @change="addConfirm"></el-checkbox>
          </div>

        <div class="no-data-img" v-if="goodsData.length == 0">
          <img src="../../assets/image/no-data.png" alt="">
          <div class="tips">暂无数据</div>
        </div>
      </div>
      <div class="block" style="margin: 20px 0px; text-align: right;">
      	<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
      	 :page-sizes="[10, 15, 20, 25]" :page-size="form.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>
    <el-dialog title="更新" :visible.sync="isShowDialog"  width="800px" class="goods-dialog">
       <div class="goods-info">
            <el-form ref="form" label-width="120px" class="el-form">
              <el-form-item label="店铺名称 :" prop="shop_name">
                <!-- 梵诺威旗舰店:disabled="fang" -->
                <el-input placeholder  v-model="goodDetail.shop_name" class="disabled" size="small" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="商品链接 :" prop="goods_url">
                <el-input placeholder v-model="goodDetail.goods_url" class="disabled" size="small" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="商品id :" prop="product_id">
                <el-input placeholder v-model="goodDetail.product_id" class="disabled" size="small" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="店铺种类 :" prop="shopType">
                <el-input class="autocompletey" size="small" v-model="storeName[goodDetail.shop_type]" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="商品标题 :" prop="goods_title">
                <el-input placeholder v-model="goodDetail.goods_title" class="disabled" size="small" :disabled="true"></el-input>
              </el-form-item>

              <el-form-item label="掌柜昵称 :" prop="selle_name" v-if="tbArr.indexOf(goodDetail.shop_type) >=0">
                <!-- fang == true ? (form.goodsSeller == '' ? true : false) :  -->
                <el-input placeholder v-model="goodDetail.selle_name" class="disabled" size="small" :disabled="true"></el-input>
              </el-form-item>
            </el-form>
       </div>
       <div class="goods-img-box">
           <div class="goods-img">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :action="BASE_API_URL+'baseapi/wechart/uploadMerchantPushImg'"
                :data="uploadData"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img class="goods-main-img" :src="goodDetail.goods_img" alt="">
              </el-upload>
           </div>
       </div>
       <div class="update-btn-box">
          <div class="update-btn" @click="updateGoods">
            更新
          </div>
       </div>
    </el-dialog>
    <el-dialog
      title="添加商品"
      :visible.sync="isShowAddGoods"
      :modal-append-to-body="false"
      width="70%"
      :before-close="cancelAddGoods">
      <div>
        <el-form
          ref="goodsInfo"
          :model="goodsInfo"
          :rules="goodsRules"
          label-width="120px"
          class="goods-form"
        >
          <el-form-item label="店铺名称 :" prop="shopId">
            <el-select
              v-model="goodsInfo.shopId"
              class="form-input"
              placeholder="请选择店铺名称"
              size="small"
              filterable
              :filter-method="dataFilter"
              clearable
            >
              <el-option
                v-for="(store, index) in shopNameList"
                :key="index"
                :label="store.name"
                :value="store.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="店铺种类 :" prop="shopType">
            <el-select
              v-model="goodsInfo.shopType"
              placeholder="请选择店铺种类"
              size="small"
              class="form-input"
            >
              <el-option v-for="(type, key) in platformType" :key="key" :label="type" :value="key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品链接 :" prop="goodsUrl">
            <el-input
              placeholder="请输入商品链接"
              v-model="goodsInfo.goodsUrl"
              size="small"
              class="form-input"
            ></el-input>
            <div style="display: inline-block;">
              <el-button
                class="form-btn"
                @click="grabGoodsInfo"
              >抓取商品信息
              </el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="商品id :" prop="productId">
            <el-input
              placeholder
              v-model="goodsInfo.productId"
              size="small"
              class="form-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品标题 :" prop="goodsTitle">
            <el-input
              placeholder="请输入商品标题"
              v-model="goodsInfo.goodsTitle"
              size="small"
              class="form-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="店铺名称 :" prop="shopName">
            <el-input
              v-model="goodsInfo.shopName"
              class="form-input"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="拍下单价 :" prop="showMoney">
            <el-input
              v-model.number="goodsInfo.showMoney"
              type="number"
              class="form-input"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品归属地 :" prop="goodsAddress">
            <el-input
              v-model="goodsInfo.goodsAddress"
              class="form-input"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="上传图片 :" prop="goodsImg">
            <!--            <el-upload-->
            <!--              class="avatar-uploader"-->
            <!--              :show-file-list="false"-->
            <!--              :action="BASE_API_URL+'baseapi/wechart/uploadMerchantPushImg'"-->
            <!--              :data="uploadData"-->
            <!--              :on-success="handleAvatarSuccess"-->
            <!--              :before-upload="beforeAvatarUpload">-->
            <!--              <img class="goods-main-img" :src="goodsInfo.goodsImg" alt="">-->
            <!--            </el-upload>-->
            <el-upload
              class="avatar-uploader"
              :action="BASE_API_URL+'baseapi/wechart/uploadMerchantPushImg'"
              :show-file-list="false"
              :on-success="handleSuccessAddGoodsImg"
              :before-upload="beforeUploadAddGoodsImg">
              <img v-if="goodsInfo.goodsImg" :src="goodsInfo.goodsImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddGoods = false">取 消</el-button>
        <el-button type="primary" @click="addGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    apiGetMerchantShopList,
    apiGetGoodsInfo,
    apiDelGoods,
    apiMerchantGoods,
    apiChangeGoodsImg,
    apiDeleteShopGoods
  } from '../../request/api.js'
  import { mapGetters } from 'vuex';

  import AddGoods from "./addGoods"

export default{
  mixins: [AddGoods],
  data(){
    return {
      goodsData: [],
      shopListData: [],
      uploadData: {
        area: 'goods'
      },
      form: {
        token: '',
        page: 1,
        pageSize: 10,
        shopId: '',
        productId: '',
        shopType: ''
      },
      total: 0,
      storeName:{
        1: '淘宝',
        2: '天猫',
        3: '京东',
        4: '1688',
        13: '唯品会',
        15: '拼多多',
        20: '抖音',
      },
      isDisblead: false,
      shopTypeData: [
        {
          label: '淘宝',
          value: 1
        },
        {
          label: '天猫',
          value: 2
        },
        {
          label: '京东',
          value: 3
        },
        {
          label: '1688',
          value: 4
        },
        {
          label: '唯品会',
          value: 13
        },
        {
          label: '抖音',
          value: 20
        },
        {
          label: '拼多多',
          value: 15
        }
      ],
      shopId: 0,
      isShowDialog: false,
      goodDetail: {},
      tbArr: [1,2],
      userToken: window.localStorage.getItem('token'),
      merchantData: JSON.parse(window.localStorage.getItem('merchantConfig'))
    }
  },
  created() {
    if (this.merchantData.only_douyin == 1){
      this.shopTypeData = []
      this.shopTypeData.push({
        label: '抖音',
        value: 20
      })
      this.platformType = []
      this.platformType = { 20: "抖音" }
    }
    this.form.token = this.userToken
    this.getShopList()
    this.getGoodsData()
  },
  methods:{
    resetSearchParam(){
      this.form = {
        token: this.userToken,
        page: 1,
        pageSize: 10,
        shopId: '',
        productId: '',
        shopType: ''
      }
      this.getGoodsData()
    },
    updateGoods(){
      var goodsUrl = this.goodDetail.goods_url
      if (this.goodDetail.goods_url != '') {
        if (goodsUrl.indexOf('detail.tmall.com') != -1 || goodsUrl.indexOf('item.taobao.com') != -1 ||
          goodsUrl.indexOf('item.jd.com') != -1 || goodsUrl.indexOf('item.m.jd.com') != -1 || goodsUrl.indexOf('yangkeduo.com') != -1) {
          // this.fullscreenLoading = true;
          this.$loading.show('更新中')
          apiGetGoodsInfo({
            goodsUrl: escape(this.goodDetail.goods_url),
            token: this.userToken
          }).then(res =>{
            if (res.code == 1){
              this.goodDetail.goods_title = res.msg.name;
              this.goodDetail.seller_name = res.msg.seller_name;
              this.goodDetail.shop_name = res.msg.shop_name;
              this.goodDetail.shop_type = res.msg.shop_type;
              this.goodDetail.goods_img = res.msg.goods_img;
              this.goodDetail.product_id = res.msg.product_id
              this.$loading.hide()
              return this.$message.success("更新成功");
            } else {
              this.$loading.hide()
              // this.fullscreenLoading = false;
              this.goodDetail.goods_title = "";
              this.goodDetail.selle_name = "";
              this.goodDetail.shop_name = "";
              this.goodDetail.shop_type = "";
              if(goodsUrl.indexOf('yangkeduo.com') != -1){
                this.goodDetail.product_id = this.goodDetail.goods_url.split('goods_id=')[1].split('&')[0]

              }
              if(goodsUrl.indexOf('item.jd.com') != -1){
                this.goodDetail.product_id = this.goodDetail.goods_url.split('com/')[1].split('.html')[0]
              }
              return this.$message.error(result.msg);
            }
          }).catch(res => {
            this.$message.error(res.msg)
          })
        } else if (this.goodDetail.goods_url.indexOf('m.vip.com') != -1 || this.goodDetail.goods_url.indexOf('detail.vip.com') != -1) {

          this.goodDetail.goods_title = "";
          this.goodDetail.selle_name = "";
          this.goodDetail.shop_name = "";
          this.goodDetail.shop_type = "";
        }

      } else {
        return this.$message.error("更新失败，没有商品链接");
      }
    },

    getShopId(item){
      this.goodDetail = item
      // this.shopId = id
      this.isShowDialog = true
    },
    showConfirm(id){
      this.$confirm('此操作将删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteGoods(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addConfirm(val){
      // console.log('推广' + val)
      // this.$confirm('推广该商品, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   console.log('推广' + id)
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消推广'
      //   });
      // });
    },
    deleteGoods(id){
      if (this.isDisblead) {
        return
      }
      this.isDisblead = true
      apiDeleteShopGoods({
        token: this.userToken,
        goodsId: id
      }).then(res =>{
        if (res.code == 1){
          this.$message.success('删除成功');
          this.getGoodsData()
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$message.error(res.msg)
      })
    },
    getShopList() {
      this.$isClick(true);
      apiGetMerchantShopList({
        token: this.userToken
      }).then(res =>{
        this.$isClick(false);
        if (res.code == 1){
          for (var i in res.msg.merchant_shop_list) {
            this.shopListData.push({
              name: this.storeName[res.msg.merchant_shop_list[i].type] + '-' + res.msg.merchant_shop_list[i].name,
              id: res.msg.merchant_shop_list[i].id
            })
          }
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },
    getGoodsData() {
      this.$isClick(true);
      apiMerchantGoods(this.form).then(res =>{
        this.$isClick(false);
        if (res.code == 1){
          this.goodsData = res.msg.res
          this.total = res.msg.con
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getGoodsData()
    },
    handleCurrentChange(val) {
      this.form.page = val;
      this.getGoodsData()
    },
    handleAvatarSuccess(res, file) {
      this.$loading.show('上传中')
      apiChangeGoodsImg({
        token: this.userToken,
        goodsId: this.goodDetail.id,
        imgUrl: res.msg
      }).then(res =>{
        if (res.code == 1){
          this.$message.success('更改成功');
          this.isShowDialog = false
          this.getGoodsData()
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$message.error(res.msg)
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isLt2M;
      // let _this = this
      // return new Promise((resolve, reject) => {
      //   let isLt2M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于10MB
      //   if(!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 10MB!');
      //     reject()
      //   }
      //   let image = new Image(), resultBlob = '';
      //   image.src = URL.createObjectURL(file);
      //   image.onload = () => {
      //     // 调用方法获取blob格式，方法写在下边
      //     resultBlob = _this.compressUpload(image);
      //     resolve(resultBlob)
      //   }
      //   image.onerror = () => {
      //      reject()
      //   }
      // })
    },
    compressUpload(image) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let initSize = image.src.length
      let { width } = image, { height } = image
      canvas. width = width
      canvas.height = height
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(image, 0, 0, width, height)

      // 进行最小压缩0.1
      let compressData = canvas.toDataURL('image/jpeg', 0.1)

      // 压缩后调用方法进行base64转Blob，方法写在下边
      let blobImg = this.dataURItoBlob(compressData)
      return blobImg
    },
    /* base64转Blob对象 */
    dataURItoBlob(data) {
      let byteString;
      if(data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(data.split(',')[1])
      }else {
        byteString = unescape(data.split(',')[1])
      }
      let mimeString = data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0];
      let ia = new Uint8Array(byteString.length)
      for( let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], {type: mimeString})
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  }
}
</script>

<style lang="less">
#goods-manage {

  .table-box {
    .tips {
      color: red;
      margin-top: -16px;
      margin-bottom: 16px;
    }
    .goods-list {
      .img-box {
        display: inline-block;
        margin: 8px;
        width: 150px;
        box-shadow: 0px 0px 3px #666;
        padding: 5px;
        border-radius: 5px;
        position: relative;
        cursor: pointer;

        .close-btn {
          position: absolute;
          right: -7px;
          top: -10px;
          color: red;
          font-size: 20px;
          display: none;
        }
        //.success-btn {
        //  position: absolute;
        //  right: 7px;
        //  top: -10px;
        //  color: red;
        //  font-size: 20px;
        //  display: none;
        //}
        .text{
          font-size: 14px;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
        .delete-icon {
          color: red;
          padding: 3px;
          cursor: pointer;
        }
        .img{
          width: 150px;
          height: 150px;
        }
      }
      .img-box:hover{
        .close-btn {
          display: inline-block;
        }

      }
    }
  }
  .goods-dialog {
    .goods-info {
      display: inline-block;
      width: 500px;
      margin-right: 20px;
    }
    .goods-img-box {
      display: inline-block;
      vertical-align: top;
      .goods-img {
        width:200px;
        height: 200px;
        border: 1px solid;
        margin-top: 53px;
      }
    }
    .avatar-uploader .el-upload {
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: @themeColor;
    }
    .goods-main-img{
      width: 200px;
      height: 200px;
    }
    .update-btn-box {
      text-align: center;
      .update-btn {
        display: inline-block;
        background-color: @themeColor;
        color: #fff;
        padding: 8px 30px;
        border-radius: 5px;
        margin-top: 20px;
        cursor: pointer;
        // margin: 0 auto;
      }
    }
  }
  .no-data-img {
    text-align: center;
    margin-top: 80px;
    .tips{
      font-size: 14px;
      margin-top: 10px;
      color: @fontSubtitleColor;
    }
  }
}
</style>
